package com.jhxy.algorithm.maxprofit;

import com.jhxy.algorithm.util.InputsForMaxProfit;
import com.jhxy.algorithm.util.PrintTool;

import java.util.List;

/**
 * 买卖股票的最佳时机：归并法
 */
public class MaxProfit {


    private int maxProfit(int[] prices) {
        int[] deltaPrices = new int[prices.length - 1];
        for (int i = 0; i < deltaPrices.length; i++) {
            deltaPrices[i] = prices[i + 1] - prices[i];
        }

        int maxProfit = maxSubArray(deltaPrices);
        return Math.max(maxProfit, 0);

    }


    private int maxSubArray(int[] deltaPrices) {
        int maxSum = Integer.MIN_VALUE;

        int sum = 0;

        for (int i = 0; i < deltaPrices.length; i++) {
            sum += deltaPrices[i];

            if (maxSum < sum) {
                maxSum = sum;
            }

            if (sum < 0) {
                sum = 0;
            }
        }
        return maxSum;
    }


    public static void main(String args[]) {
        InputsForMaxProfit inputs = new InputsForMaxProfit("1,2,3,4,5,6;7,1,5,3,6,4;7,6,4,3,1");
        PrintTool print = new PrintTool();
        MaxProfit ins = new MaxProfit();
        int i = 1;
        for (List<Object> input : inputs.inputs) {
            System.out.println("=================第" + (i++) + "组输入输出=================");
            print.printArray((int[]) input.get(0));
            int maxProfit = ins.maxProfit((int[]) input.get(0));
            System.out.println("");
            System.out.println(maxProfit);
            System.out.println("");
        }
    }

}
